package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.Result;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.Date;

@RestController
@RequestMapping("index")
public class IndexController {
    @Autowired
    private PortsService portsService;
    @Autowired
    private CountriesService countriesService;
    @Autowired
    private PortServicesService portServicesService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductImageService productImageService;
    @Autowired
    private PortProductRelationService portProductRelationService;
    @Autowired
    private CategoryLevel2Service categoryLevel2Service;

    // ===== 港口相关接口 =====
    
    /**
     * 获取所有启用的港口列表（用于港口选择）
     */
    @GetMapping("/ports")
    public Result getAllPorts() {
        try {
            QueryWrapper<Ports> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1); // 只获取启用的港口
            queryWrapper.orderByDesc("is_popular"); // 热门港口排在前面
            queryWrapper.orderByAsc("name"); // 其次按名称排序
            
            List<Ports> ports = portsService.list(queryWrapper);
            
            // 构建返回数据，包含港口基本信息和国家信息
            List<Map<String, Object>> portsWithDetails = new ArrayList<>();
            for (Ports port : ports) {
                Map<String, Object> portInfo = new HashMap<>();
                portInfo.put("id", port.getId());
                portInfo.put("name", port.getName());
                portInfo.put("portCode", port.getPortCode());
                portInfo.put("description", port.getDescription());
                portInfo.put("region", port.getRegion());
                portInfo.put("timezone", port.getTimezone());
                portInfo.put("isPopular", port.getIsPopular());
                
                // 获取国家信息
                Countries country = countriesService.getById(port.getCountryId());
                if (country != null) {
                    portInfo.put("countryId", country.getId());
                    portInfo.put("countryName", country.getName());
                    portInfo.put("countryNameEn", country.getNameEn());
                    portInfo.put("flag", country.getFlag());
                }
                
                // 统计该港口的商品数量
                QueryWrapper<PortProductRelation> relationQuery = new QueryWrapper<>();
                relationQuery.eq("port_id", port.getId().intValue()); // 转换为Integer类型
                long productCount = portProductRelationService.count(relationQuery);
                portInfo.put("productCount", productCount);
                
                portsWithDetails.add(portInfo);
            }
            
            return Result.success(portsWithDetails);
        } catch (Exception e) {
            return Result.error("获取港口列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据港口ID获取该港口的商品列表（支持分页和搜索）
     * @param portId 港口ID
     * @param page 页码，默认1
     * @param size 每页大小，默认12
     * @param keyword 搜索关键词，可选
     * @param sortBy 排序方式：price_asc, price_desc, score_desc, sales_desc，默认score_desc
     */
    @GetMapping("/ports/{portId}/products")
    public Result getProductsByPort(@PathVariable Long portId,
                                   @RequestParam(defaultValue = "1") Integer page,
                                   @RequestParam(defaultValue = "12") Integer size,
                                   @RequestParam(required = false) String keyword,
                                   @RequestParam(defaultValue = "score_desc") String sortBy) {
        System.out.println("=== 港口商品查询方法被调用 ===");
        System.out.println("接收到的参数 - portId: " + portId + ", page: " + page + ", size: " + size + ", keyword: " + keyword + ", sortBy: " + sortBy);
        try {
            // 验证港口是否存在
            Ports port = portsService.getById(portId);
            if (port == null) {
                return Result.error("港口不存在");
            }

            // 查询港口商品关联关系 - 修复类型转换问题
            QueryWrapper<PortProductRelation> relationQuery = new QueryWrapper<>();
            relationQuery.eq("port_id", portId.intValue()); // 转换为Integer类型
            List<PortProductRelation> relations = portProductRelationService.list(relationQuery);
            
            // 添加调试日志
            System.out.println("=== 调试信息 ===");
            System.out.println("查询港口ID: " + portId);
            System.out.println("港口信息: " + port.getName());
            System.out.println("找到的关联关系数量: " + relations.size());
            if (!relations.isEmpty()) {
                System.out.println("关联的商品ID列表: ");
                for (PortProductRelation relation : relations) {
                    System.out.println("- 商品ID: " + relation.getProductId());
                }
            }

            if (relations.isEmpty()) {
                Map<String, Object> emptyResponse = buildEmptyResponse(port, page, size);
                return Result.success(emptyResponse);
            }

            // 提取商品ID列表
            List<Long> productIds = new ArrayList<>();
            for (PortProductRelation relation : relations) {
                productIds.add(Long.valueOf(relation.getProductId())); // 转换为Long类型用于Product查询
            }

            // 构建商品查询条件
            QueryWrapper<Product> productQuery = new QueryWrapper<>();
            productQuery.in("product_id", productIds);
            productQuery.eq("status", 1); // 只查询上架商品
            
            // 添加搜索条件
            if (keyword != null && !keyword.trim().isEmpty()) {
                productQuery.like("name", keyword.trim());
            }
            
            // 添加排序条件
            switch (sortBy) {
                case "price_asc":
                    productQuery.orderByAsc("price");
                    break;
                case "price_desc":
                    productQuery.orderByDesc("price");
                    break;
                case "sales_desc":
                    productQuery.orderByDesc("sales_count");
                    break;
                case "score_desc":
                default:
                    productQuery.orderByDesc("avg_score");
                    productQuery.orderByDesc("sales_count");
                    break;
            }

            // 分页查询
            IPage<Product> pageRequest = new Page<>(page, size);
            IPage<Product> productPage = productService.page(pageRequest, productQuery);

            // 构建返回数据 - 使用批量方法提高性能
            List<Map<String, Object>> productsWithDetails = buildProductInfoList(productPage.getRecords());
            
            // 为每个商品添加港口特定信息
            for (Map<String, Object> productInfo : productsWithDetails) {
                // 添加该商品在该港口的特殊信息（如果有）
                productInfo.put("currentPort", buildPortInfo(port));
            }

            // 构建响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("port", buildPortInfo(port));
            response.put("products", productsWithDetails);
            response.put("totalCount", productPage.getTotal());
            response.put("currentPage", page);
            response.put("pageSize", size);
            response.put("totalPages", productPage.getPages());
            response.put("hasNext", page < productPage.getPages());
            response.put("hasPrev", page > 1);
            response.put("keyword", keyword);
            response.put("sortBy", sortBy);

            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取港口商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 简化版本：根据港口ID获取该港口的商品列表（不分页，适合前端快速调用）
     * @param portId 港口ID
     * @param limit 限制返回数量，默认20
     */
    @GetMapping("/ports/{portId}/products/simple")
    public Result getSimpleProductsByPort(@PathVariable Long portId,
                                        @RequestParam(defaultValue = "20") Integer limit) {
        try {
            // 验证港口是否存在
            Ports port = portsService.getById(portId);
            if (port == null) {
                return Result.error("港口不存在");
            }

            // 查询港口商品关联关系
            QueryWrapper<PortProductRelation> relationQuery = new QueryWrapper<>();
            relationQuery.eq("port_id", portId.intValue()); // 转换为Integer类型
            List<PortProductRelation> relations = portProductRelationService.list(relationQuery);

            if (relations.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("portId", portId);
                response.put("portName", port.getName());
                response.put("products", new ArrayList<>());
                response.put("totalCount", 0);
                return Result.success(response);
            }

            // 提取商品ID列表
            List<Long> productIds = new ArrayList<>();
            for (PortProductRelation relation : relations) {
                productIds.add(Long.valueOf(relation.getProductId()));
            }

            // 构建商品查询条件
            QueryWrapper<Product> productQuery = new QueryWrapper<>();
            productQuery.in("product_id", productIds);
            productQuery.eq("status", 1); // 只查询上架商品
            productQuery.orderByDesc("avg_score"); // 按评分降序排列
            productQuery.orderByDesc("sales_count"); // 其次按销量降序排列
            productQuery.last("LIMIT " + limit); // 限制返回数量

            List<Product> products = productService.list(productQuery);

            // 构建返回数据 - 使用批量方法提高性能
            List<Map<String, Object>> productsWithDetails = buildProductInfoList(products);

            // 构建响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("portId", portId);
            response.put("portName", port.getName());
            response.put("portCode", port.getPortCode());
            response.put("products", productsWithDetails);
            response.put("totalCount", relations.size());
            response.put("returnedCount", products.size());

            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取港口商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取港口商品分类统计
     * @param portId 港口ID
     */
    @GetMapping("/ports/{portId}/categories")
    public Result getPortProductCategories(@PathVariable Long portId) {
        try {
            // 验证港口是否存在
            Ports port = portsService.getById(portId);
            if (port == null) {
                return Result.error("港口不存在");
            }

            // 查询港口商品关联关系
            QueryWrapper<PortProductRelation> relationQuery = new QueryWrapper<>();
            relationQuery.eq("port_id", portId.intValue()); // 转换为Integer类型
            List<PortProductRelation> relations = portProductRelationService.list(relationQuery);

            if (relations.isEmpty()) {
                return Result.success(new ArrayList<>());
            }

            // 提取商品ID列表
            List<Long> productIds = new ArrayList<>();
            for (PortProductRelation relation : relations) {
                productIds.add(relation.getProductId().longValue()); // 转换为Long类型
            }

            // 查询商品信息（只查询上架商品）
            QueryWrapper<Product> productQuery = new QueryWrapper<>();
            productQuery.in("product_id", productIds);
            productQuery.eq("status", 1);
            productQuery.select("level2_id"); // 只查询分类ID
            List<Product> products = productService.list(productQuery);

            // 统计分类信息（这里需要根据实际的分类服务来实现）
            Map<Long, Integer> categoryCount = new HashMap<>();
            for (Product product : products) {
                if (product.getLevel2Id() != null) {
                    categoryCount.put(product.getLevel2Id(), 
                        categoryCount.getOrDefault(product.getLevel2Id(), 0) + 1);
                }
            }

            List<Map<String, Object>> categories = new ArrayList<>();
            for (Map.Entry<Long, Integer> entry : categoryCount.entrySet()) {
                Map<String, Object> categoryInfo = new HashMap<>();
                categoryInfo.put("categoryId", entry.getKey());
                categoryInfo.put("productCount", entry.getValue());
                // 这里可以根据需要添加分类名称等信息
                categories.add(categoryInfo);
            }

            return Result.success(categories);
        } catch (Exception e) {
            return Result.error("获取港口商品分类失败：" + e.getMessage());
        }
    }

    /**
     * 获取港口商品价格区间统计
     * @param portId 港口ID
     */
    @GetMapping("/ports/{portId}/price-range")
    public Result getPortProductPriceRange(@PathVariable Long portId) {
        try {
            // 验证港口是否存在
            Ports port = portsService.getById(portId);
            if (port == null) {
                return Result.error("港口不存在");
            }

            // 查询港口商品关联关系
            QueryWrapper<PortProductRelation> relationQuery = new QueryWrapper<>();
            relationQuery.eq("port_id", portId.intValue()); // 转换为Integer类型
            List<PortProductRelation> relations = portProductRelationService.list(relationQuery);

            if (relations.isEmpty()) {
                Map<String, Object> priceRange = new HashMap<>();
                priceRange.put("minPrice", 0);
                priceRange.put("maxPrice", 0);
                priceRange.put("avgPrice", 0);
                return Result.success(priceRange);
            }

            // 提取商品ID列表
            List<Long> productIds = new ArrayList<>();
            for (PortProductRelation relation : relations) {
                productIds.add(Long.valueOf(relation.getProductId())); // 转换为Long类型
            }

            // 查询商品价格信息
            QueryWrapper<Product> productQuery = new QueryWrapper<>();
            productQuery.in("product_id", productIds);
            productQuery.eq("status", 1);
            productQuery.isNotNull("price");
            productQuery.select("price");
            List<Product> products = productService.list(productQuery);

            if (products.isEmpty()) {
                Map<String, Object> priceRange = new HashMap<>();
                priceRange.put("minPrice", 0);
                priceRange.put("maxPrice", 0);
                priceRange.put("avgPrice", 0);
                return Result.success(priceRange);
            }

            // 计算价格统计
            BigDecimal minPrice = products.get(0).getPrice();
            BigDecimal maxPrice = products.get(0).getPrice();
            BigDecimal totalPrice = BigDecimal.ZERO;

            for (Product product : products) {
                BigDecimal price = product.getPrice();
                if (price.compareTo(minPrice) < 0) {
                    minPrice = price;
                }
                if (price.compareTo(maxPrice) > 0) {
                    maxPrice = price;
                }
                totalPrice = totalPrice.add(price);
            }

            BigDecimal avgPrice = totalPrice.divide(new BigDecimal(products.size()), 2, BigDecimal.ROUND_HALF_UP);

            Map<String, Object> priceRange = new HashMap<>();
            priceRange.put("minPrice", minPrice);
            priceRange.put("maxPrice", maxPrice);
            priceRange.put("avgPrice", avgPrice);
            priceRange.put("productCount", products.size());

            return Result.success(priceRange);
        } catch (Exception e) {
            return Result.error("获取港口商品价格区间失败：" + e.getMessage());
        }
    }

    // ===== 原有方法保持不变 =====
    
    /**
     * 获取所有国家及其港口数量（用于国家选择展示）
     */
    @GetMapping("/countries/withPortCount")
    public Result getCountriesWithPortCount() {
        try {
            // 获取所有启用的国家
            QueryWrapper<Countries> countryQuery = new QueryWrapper<>();
            countryQuery.eq("status", 1);
            countryQuery.orderByAsc("sort_order"); // 使用实际的sort_order字段
            List<Countries> countries = countriesService.list(countryQuery);

            // 获取所有启用的港口
            QueryWrapper<Ports> portQuery = new QueryWrapper<>();
            portQuery.eq("status", 1);
            List<Ports> ports = portsService.list(portQuery);

            // 统计每个国家的港口数量
            List<Map<String, Object>> result = new ArrayList<>();
            for (Countries country : countries) {
                Map<String, Object> countryInfo = new HashMap<>();
                countryInfo.put("id", country.getId());
                countryInfo.put("name", country.getName());
                // 使用Countries实体类的实际字段值
                countryInfo.put("nameEn", country.getNameEn());
                countryInfo.put("flag", country.getFlag());
                countryInfo.put("sortOrder", country.getSortOrder());

                // 计算该国家的港口数量
                long portCount = ports.stream()
                        .filter(port -> port.getCountryId().equals(country.getId()))
                        .count();
                countryInfo.put("portCount", portCount);

                result.add(countryInfo);
            }

            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取国家港口数量统计失败");
        }
    }

    /**
     * 根据国家ID获取该国家的所有港口
     */
    @GetMapping("/countries/{countryId}/ports")
    public Result getPortsByCountry(@PathVariable Long countryId) {
        try {
            // 验证国家是否存在
            Countries country = countriesService.getById(countryId);
            if (country == null) {
                return Result.error("国家不存在");
            }

            // 获取该国家的所有启用港口
            QueryWrapper<Ports> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("country_id", countryId);
            queryWrapper.eq("status", 1);
            queryWrapper.orderByDesc("is_popular").orderByAsc("name");
            List<Ports> ports = portsService.list(queryWrapper);

            // 获取每个港口的服务信息
            List<Map<String, Object>> portsWithServices = new ArrayList<>();
            for (Ports port : ports) {
                Map<String, Object> portInfo = new HashMap<>();
                portInfo.put("id", port.getId());
                portInfo.put("name", port.getName());
                portInfo.put("portCode", port.getPortCode());
                portInfo.put("description", port.getDescription());
                portInfo.put("region", port.getRegion());
                portInfo.put("timezone", port.getTimezone());
                portInfo.put("isPopular", port.getIsPopular());
                portInfo.put("countryName", country.getName());
                // 使用Countries实体类的实际字段值
                portInfo.put("countryNameEn", country.getNameEn());
                portInfo.put("flag", country.getFlag());

                // 获取港口服务
                QueryWrapper<PortServices> serviceQuery = new QueryWrapper<>();
                serviceQuery.eq("port_id", port.getId());
                serviceQuery.eq("status", 1);
                List<PortServices> services = portServicesService.list(serviceQuery);

                portInfo.put("services", services);
                portInfo.put("serviceCount", services.size());

                portsWithServices.add(portInfo);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("country", country);
            response.put("ports", portsWithServices);
            response.put("totalPorts", ports.size());

            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取国家港口列表失败");
        }
    }

    /**
     * 获取热门港口（is_popular = 1）
     */
    @GetMapping("/ports/popular")
    public Result getPopularPorts() {
        try {
            QueryWrapper<Ports> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1);
            queryWrapper.eq("is_popular", 1);
            queryWrapper.orderByAsc("name");
            List<Ports> popularPorts = portsService.list(queryWrapper);

            // 获取每个港口的国家信息和服务
            List<Map<String, Object>> portsWithDetails = new ArrayList<>();
            for (Ports port : popularPorts) {
                Map<String, Object> portInfo = new HashMap<>();
                portInfo.put("id", port.getId());
                portInfo.put("name", port.getName());
                portInfo.put("portCode", port.getPortCode());
                portInfo.put("description", port.getDescription());
                portInfo.put("region", port.getRegion());
                portInfo.put("timezone", port.getTimezone());
                portInfo.put("isPopular", port.getIsPopular());

                // 获取国家信息
                Countries country = countriesService.getById(port.getCountryId());
                if (country != null) {
                    portInfo.put("countryName", country.getName());
                    // 使用Countries实体类的实际字段值
                    portInfo.put("countryNameEn", country.getNameEn());
                    portInfo.put("flag", country.getFlag());
                }

                // 获取港口服务
                QueryWrapper<PortServices> serviceQuery = new QueryWrapper<>();
                serviceQuery.eq("port_id", port.getId());
                serviceQuery.eq("status", 1);
                List<PortServices> services = portServicesService.list(serviceQuery);

                portInfo.put("services", services);
                portInfo.put("serviceCount", services.size());

                portsWithDetails.add(portInfo);
            }

            return Result.success(portsWithDetails);
        } catch (Exception e) {
            return Result.error("获取热门港口失败");
        }
    }
    @GetMapping("/ports/{portId}/detail")
    public Result getPortDetail(@PathVariable Long portId) {
        try {
            // 获取港口信息
            Ports port = portsService.getById(portId);
            if (port == null) {
                return Result.error("港口不存在");
            }

            // 获取国家信息
            Countries country = countriesService.getById(port.getCountryId());

            // 获取港口服务
            QueryWrapper<PortServices> serviceQuery = new QueryWrapper<>();
            serviceQuery.eq("port_id", portId);
            serviceQuery.eq("status", 1);
            List<PortServices> services = portServicesService.list(serviceQuery);

            Map<String, Object> portDetail = new HashMap<>();
            portDetail.put("id", port.getId());
            portDetail.put("name", port.getName());
            portDetail.put("portCode", port.getPortCode());
            portDetail.put("description", port.getDescription());
            portDetail.put("region", port.getRegion());
            portDetail.put("timezone", port.getTimezone());
            portDetail.put("isPopular", port.getIsPopular());
            portDetail.put("services", services);
            portDetail.put("serviceCount", services.size());

            if (country != null) {
                portDetail.put("country", country);
            }

            return Result.success(portDetail);
        } catch (Exception e) {
            return Result.error("获取港口详情失败");
        }
    }
    @GetMapping("/ports/byRegion")
    public Result getPortsByRegion(@RequestParam String region) {
        try {
            QueryWrapper<Ports> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("region", region);
            queryWrapper.eq("status", 1);
            queryWrapper.orderByDesc("is_popular").orderByAsc("name");
            List<Ports> ports = portsService.list(queryWrapper);

            List<Map<String, Object>> portsWithDetails = new ArrayList<>();
            for (Ports port : ports) {
                Map<String, Object> portInfo = new HashMap<>();
                portInfo.put("id", port.getId());
                portInfo.put("name", port.getName());
                portInfo.put("portCode", port.getPortCode());
                portInfo.put("description", port.getDescription());
                portInfo.put("region", port.getRegion());
                portInfo.put("timezone", port.getTimezone());
                portInfo.put("isPopular", port.getIsPopular());

                // 获取国家信息
                Countries country = countriesService.getById(port.getCountryId());
                if (country != null) {
                    portInfo.put("countryName", country.getName());
                    portInfo.put("countryNameEn", country.getNameEn());
                    portInfo.put("flag", country.getFlag());
                }

                // 获取港口服务
                QueryWrapper<PortServices> serviceQuery = new QueryWrapper<>();
                serviceQuery.eq("port_id", port.getId());
                serviceQuery.eq("status", 1);
                List<PortServices> services = portServicesService.list(serviceQuery);

                portInfo.put("services", services);
                portInfo.put("serviceCount", services.size());

                portsWithDetails.add(portInfo);
            }

            return Result.success(portsWithDetails);
        } catch (Exception e) {
            return Result.error("根据地区获取港口失败");
        }
    }
    
    //首页模块
    //3.2.1 目的港管理
    //首次打开系统强制用户选择已开通的目的港
    //目的港选择影响商品价格显示，不同港口商品价格可能会有浮动
    //支持在首页修改目的港
    //3.2.2 搜索功能
    //关键词模糊搜索，支持商品名称、规格等属性检索
    //热门搜索词展示:近期搜索排名前 10 的关键词 +平台推广产品
    //搜索历史记录管理:支持查看、删除最近搜索记录
    //3.2.3 内容展示区
    //轮播图:展示平台活动、促销信息，支持点击跳转活动页
    //导航栏:两行五列布局，支持左右滑动浏览更多分类
    //专题活动区:展示特定系列商品的专题促销活动
    //分类导航:直接展示热门分类到首页，点击进入分类列表页
    //3.2.4 推荐商品
    //个性化推荐算法:基于用户历史订单、浏览记录、收藏商品进行推荐
    //推荐列表展示:商品封面、名称、价格、销量等核心信息
    //支持刷新推荐列表和查看更多推荐商品

    /**
     * 获取评分4.7及以上的高评分商品
     * 用于首页推荐展示，关联查询商品图片
     */
    @GetMapping("/products/highScore")
    public Result getHighScoreProducts() {
        try {
            // 创建查询条件：评分 >= 4.7 且商品上架
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("avg_score", 4.7);  // 评分 >= 4.7
            queryWrapper.eq("status", 1);       // 商品上架状态
            queryWrapper.orderByDesc("avg_score"); // 按评分降序排列
            queryWrapper.orderByDesc("sales_count"); // 其次按销量降序排列
            
            List<Product> highScoreProducts = productService.list(queryWrapper);
            
            // 构建返回数据，包含商品的核心信息和图片 - 使用批量方法提高性能
            List<Map<String, Object>> productsWithDetails = buildProductInfoList(highScoreProducts);
            
            Map<String, Object> response = new HashMap<>();
            response.put("products", productsWithDetails);
            response.put("totalCount", highScoreProducts.size());
            response.put("minScore", 4.7);
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("获取高评分商品失败：" + e.getMessage());
        }
    }

    /**
     * 获取港口商品统计信息
     * @param portId 港口ID
     */
    @GetMapping("/ports/{portId}/products/stats")
    public Result getPortProductStats(@PathVariable Long portId) {
        try {
            // 验证港口是否存在
            Ports port = portsService.getById(portId);
            if (port == null) {
                return Result.error("港口不存在");
            }

            // 查询港口商品关联总数
            QueryWrapper<PortProductRelation> relationQuery = new QueryWrapper<>();
            relationQuery.eq("port_id", portId.intValue()); // 转换为Integer类型
            long totalRelations = portProductRelationService.count(relationQuery);

            if (totalRelations == 0) {
                Map<String, Object> stats = new HashMap<>();
                stats.put("portId", portId);
                stats.put("portName", port.getName());
                stats.put("totalProducts", 0);
                stats.put("availableProducts", 0);
                stats.put("avgScore", 0);
                stats.put("totalSales", 0);
                return Result.success(stats);
            }

            // 获取关联的商品ID列表
            List<PortProductRelation> relations = portProductRelationService.list(relationQuery);
            List<Long> productIds = new ArrayList<>();
            for (PortProductRelation relation : relations) {
                productIds.add(Long.valueOf(relation.getProductId())); // 转换为Long类型
            }

            // 统计上架商品数量
            QueryWrapper<Product> availableQuery = new QueryWrapper<>();
            availableQuery.in("product_id", productIds);
            availableQuery.eq("status", 1);
            long availableCount = productService.count(availableQuery);

            // 获取商品统计信息
            List<Product> availableProducts = productService.list(availableQuery);
            
            // 计算平均评分和总销量
            BigDecimal totalScore = BigDecimal.ZERO;
            Integer totalSales = 0;
            int scoreCount = 0;

            for (Product product : availableProducts) {
                if (product.getAvgScore() != null) {
                    totalScore = totalScore.add(product.getAvgScore());
                    scoreCount++;
                }
                if (product.getSalesCount() != null) {
                    totalSales += product.getSalesCount();
                }
            }

            BigDecimal avgScore = scoreCount > 0 ? 
                totalScore.divide(new BigDecimal(scoreCount), 2, BigDecimal.ROUND_HALF_UP) : 
                BigDecimal.ZERO;

            Map<String, Object> stats = new HashMap<>();
            stats.put("portId", portId);
            stats.put("portName", port.getName());
            stats.put("portCode", port.getPortCode());
            stats.put("totalProducts", totalRelations);
            stats.put("availableProducts", availableCount);
            stats.put("avgScore", avgScore);
            stats.put("totalSales", totalSales);

            return Result.success(stats);
        } catch (Exception e) {
            return Result.error("获取港口商品统计失败：" + e.getMessage());
        }
    }

    // ===== 搜索功能相关接口 =====
    
    /**
     * 商品模糊查询接口
     * 支持按商品名称、供应商进行模糊搜索
     * @param keyword 搜索关键词
     * @param page 页码，默认1
     * @param size 每页大小，默认12
     * @param sortBy 排序方式：price_asc, price_desc, score_desc, sales_desc，默认score_desc
     * @return 搜索结果
     */
    @GetMapping("/search/products")
    public Result searchProducts(@RequestParam String keyword,
                                @RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "12") Integer size,
                                @RequestParam(defaultValue = "score_desc") String sortBy) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return Result.error("搜索关键词不能为空");
            }
            
            String trimmedKeyword = keyword.trim();
            System.out.println("=== 商品搜索开始 ===");
            System.out.println("搜索关键词: " + trimmedKeyword);
            System.out.println("分页参数: page=" + page + ", size=" + size + ", sortBy=" + sortBy);
            
            // 构建商品查询条件
            QueryWrapper<Product> productQuery = new QueryWrapper<>();
            productQuery.eq("status", 1); // 只搜索上架商品
            
            // 模糊搜索：商品名称
            productQuery.like("name", trimmedKeyword);
            
            // 添加排序条件
            switch (sortBy) {
                case "price_asc":
                    productQuery.orderByAsc("price");
                    break;
                case "price_desc":
                    productQuery.orderByDesc("price");
                    break;
                case "sales_desc":
                    productQuery.orderByDesc("sales_count");
                    break;
                case "score_desc":
                default:
                    productQuery.orderByDesc("avg_score");
                    productQuery.orderByDesc("sales_count");
                    break;
            }
            
            // 分页查询
            IPage<Product> pageRequest = new Page<>(page, size);
            IPage<Product> productPage = productService.page(pageRequest, productQuery);
            
            System.out.println("搜索到商品数量: " + productPage.getTotal());
            
            // 构建返回数据
            List<Map<String, Object>> productsWithDetails = buildProductInfoList(productPage.getRecords());
            
            // 构建响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("products", productsWithDetails);
            response.put("totalCount", productPage.getTotal());
            response.put("currentPage", page);
            response.put("pageSize", size);
            response.put("totalPages", productPage.getPages());
            response.put("hasNext", page < productPage.getPages());
            response.put("hasPrev", page > 1);
            response.put("keyword", trimmedKeyword);
            response.put("sortBy", sortBy);
            response.put("searchType", "products");
            
            return Result.success(response);
        } catch (Exception e) {
            System.err.println("商品搜索失败: " + e.getMessage());
            return Result.error("商品搜索失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取热门搜索关键词
     * 返回系统推荐的热门搜索词（过滤掉查不出结果的关键词）
     */
    @GetMapping("/search/hot-keywords")
    public Result getHotSearchKeywords() {
        try {
            // 预设的热门关键词列表
            List<String> candidateKeywords = new ArrayList<>();
            candidateKeywords.add("船舶发动机");
            candidateKeywords.add("船用机油");
            candidateKeywords.add("导航设备");
            candidateKeywords.add("船舶配件");
            candidateKeywords.add("船用电器");
            candidateKeywords.add("救生设备");
            candidateKeywords.add("船用涂料");
            candidateKeywords.add("船舶仪表");
            candidateKeywords.add("船用五金");
            candidateKeywords.add("通讯设备");
            candidateKeywords.add("发动机");
            candidateKeywords.add("机油");
            candidateKeywords.add("电器");
            candidateKeywords.add("涂料");
            candidateKeywords.add("五金");
            candidateKeywords.add("设备");
            candidateKeywords.add("配件");
            candidateKeywords.add("仪表");
            
            // 过滤掉查不出结果的关键词
            List<String> validKeywords = new ArrayList<>();
            
            for (String keyword : candidateKeywords) {
                if (hasSearchResults(keyword)) {
                    validKeywords.add(keyword);
                }
                // 限制返回的热门搜索词数量为10个
                if (validKeywords.size() >= 10) {
                    break;
                }
            }
            
            // 如果过滤后的关键词太少，补充一些通用词
            if (validKeywords.size() < 5) {
                List<String> fallbackKeywords = new ArrayList<>();
                fallbackKeywords.add("船舶");
                fallbackKeywords.add("海洋");
                fallbackKeywords.add("航海");
                fallbackKeywords.add("港口");
                
                for (String keyword : fallbackKeywords) {
                    if (!validKeywords.contains(keyword) && hasSearchResults(keyword)) {
                        validKeywords.add(keyword);
                        if (validKeywords.size() >= 8) {
                            break;
                        }
                    }
                }
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("hotKeywords", validKeywords);
            response.put("updateTime", new Date());
            response.put("totalValid", validKeywords.size());
            response.put("totalCandidate", candidateKeywords.size());
            
            System.out.println("=== 热门搜索词过滤结果 ===");
            System.out.println("候选关键词数量: " + candidateKeywords.size());
            System.out.println("有效关键词数量: " + validKeywords.size());
            System.out.println("有效关键词: " + validKeywords);
            
            return Result.success(response);
        } catch (Exception e) {
            System.err.println("获取热门搜索词失败: " + e.getMessage());
            return Result.error("获取热门搜索词失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查某个关键词是否有搜索结果
     * @param keyword 关键词
     * @return 是否有结果
     */
    private boolean hasSearchResults(String keyword) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return false;
            }
            
            // 构建商品查询条件
            QueryWrapper<Product> productQuery = new QueryWrapper<>();
            productQuery.eq("status", 1); // 只搜索上架商品
            productQuery.like("name", keyword.trim());
            productQuery.last("LIMIT 1"); // 只需要知道是否有结果，限制为1条
            
            // 检查是否有匹配的商品
            long count = productService.count(productQuery);
            
            System.out.println("关键词 '" + keyword + "' 搜索结果数量: " + count);
            return count > 0;
        } catch (Exception e) {
            System.err.println("检查关键词搜索结果失败: " + keyword + ", 错误: " + e.getMessage());
            return false; // 出错时认为没有结果
        }
    }
    
    /**
     * 获取推荐分类
     * 返回热门的商品分类，用于首页分类导航展示
     * @param limit 返回数量限制，默认8个
     */
    @GetMapping("/categories/recommend")
    public Result getRecommendCategories(@RequestParam(defaultValue = "8") Integer limit) {
        try {
            System.out.println("=== 获取推荐分类 ===");
            System.out.println("限制数量: " + limit);
            
            // 查询有商品的分类，并按商品数量排序
            QueryWrapper<CategoryLevel2> categoryQuery = new QueryWrapper<>();
            categoryQuery.eq("status", 1); // 只查询启用的分类
            categoryQuery.orderByAsc("sort_order"); // 按排序顺序
            categoryQuery.last("LIMIT " + limit); // 限制返回数量
            
            List<CategoryLevel2> categories = categoryLevel2Service.list(categoryQuery);
            
            // 构建分类信息，包含该分类下的商品数量
            List<Map<String, Object>> categoriesWithDetails = new ArrayList<>();
            for (CategoryLevel2 category : categories) {
                Map<String, Object> categoryInfo = new HashMap<>();
                categoryInfo.put("level2Id", category.getLevel2Id());
                categoryInfo.put("level1Id", category.getLevel1Id());
                categoryInfo.put("name", category.getName());
                categoryInfo.put("icon", category.getIcon());
                categoryInfo.put("sortOrder", category.getSortOrder());
                
                // 统计该分类下的商品数量
                QueryWrapper<Product> productCountQuery = new QueryWrapper<>();
                productCountQuery.eq("level2_id", category.getLevel2Id());
                productCountQuery.eq("status", 1); // 只统计上架商品
                long productCount = productService.count(productCountQuery);
                categoryInfo.put("productCount", productCount);
                
                // 获取该分类下的几个热门商品作为预览
                if (productCount > 0) {
                    QueryWrapper<Product> sampleProductQuery = new QueryWrapper<>();
                    sampleProductQuery.eq("level2_id", category.getLevel2Id());
                    sampleProductQuery.eq("status", 1);
                    sampleProductQuery.orderByDesc("avg_score");
                    sampleProductQuery.orderByDesc("sales_count");
                    sampleProductQuery.last("LIMIT 3"); // 获取3个热门商品
                    
                    List<Product> sampleProducts = productService.list(sampleProductQuery);
                    List<Map<String, Object>> sampleProductInfos = buildProductInfoList(sampleProducts);
                    categoryInfo.put("sampleProducts", sampleProductInfos);
                } else {
                    categoryInfo.put("sampleProducts", new ArrayList<>());
                }
                
                categoriesWithDetails.add(categoryInfo);
            }
            
            System.out.println("返回分类数量: " + categoriesWithDetails.size());
            
            Map<String, Object> response = new HashMap<>();
            response.put("categories", categoriesWithDetails);
            response.put("totalCount", categoriesWithDetails.size());
            response.put("limit", limit);
            
            return Result.success(response);
        } catch (Exception e) {
            System.err.println("获取推荐分类失败: " + e.getMessage());
            return Result.error("获取推荐分类失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据分类ID获取该分类下的商品
     * @param categoryId 分类ID
     * @param page 页码，默认1
     * @param size 每页大小，默认12
     * @param sortBy 排序方式，默认score_desc
     */
    @GetMapping("/categories/{categoryId}/products")
    public Result getProductsByCategory(@PathVariable Long categoryId,
                                      @RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "12") Integer size,
                                      @RequestParam(defaultValue = "score_desc") String sortBy) {
        try {
            System.out.println("=== 根据分类获取商品 ===");
            System.out.println("分类ID: " + categoryId + ", page: " + page + ", size: " + size + ", sortBy: " + sortBy);
            
            // 验证分类是否存在
            CategoryLevel2 category = categoryLevel2Service.getById(categoryId);
            if (category == null) {
                return Result.error("分类不存在");
            }
            
            // 构建商品查询条件
            QueryWrapper<Product> productQuery = new QueryWrapper<>();
            productQuery.eq("level2_id", categoryId);
            productQuery.eq("status", 1); // 只查询上架商品
            
            // 添加排序条件
            switch (sortBy) {
                case "price_asc":
                    productQuery.orderByAsc("price");
                    break;
                case "price_desc":
                    productQuery.orderByDesc("price");
                    break;
                case "sales_desc":
                    productQuery.orderByDesc("sales_count");
                    break;
                case "score_desc":
                default:
                    productQuery.orderByDesc("avg_score");
                    productQuery.orderByDesc("sales_count");
                    break;
            }
            
            // 分页查询
            IPage<Product> pageRequest = new Page<>(page, size);
            IPage<Product> productPage = productService.page(pageRequest, productQuery);
            
            System.out.println("分类下商品数量: " + productPage.getTotal());
            
            // 构建返回数据
            List<Map<String, Object>> productsWithDetails = buildProductInfoList(productPage.getRecords());
            
            // 构建分类信息
            Map<String, Object> categoryInfo = new HashMap<>();
            categoryInfo.put("level2Id", category.getLevel2Id());
            categoryInfo.put("level1Id", category.getLevel1Id());
            categoryInfo.put("name", category.getName());
            categoryInfo.put("icon", category.getIcon());
            categoryInfo.put("sortOrder", category.getSortOrder());
            
            // 构建响应数据
            Map<String, Object> response = new HashMap<>();
            response.put("category", categoryInfo);
            response.put("products", productsWithDetails);
            response.put("totalCount", productPage.getTotal());
            response.put("currentPage", page);
            response.put("pageSize", size);
            response.put("totalPages", productPage.getPages());
            response.put("hasNext", page < productPage.getPages());
            response.put("hasPrev", page > 1);
            response.put("sortBy", sortBy);
            
            return Result.success(response);
        } catch (Exception e) {
            System.err.println("获取分类商品失败: " + e.getMessage());
            return Result.error("获取分类商品失败：" + e.getMessage());
        }
    }
    
    /**
     * 综合搜索接口
     * 同时搜索商品名称和分类，返回综合搜索结果
     * @param keyword 搜索关键词
     * @param page 页码，默认1
     * @param size 每页大小，默认12
     */
    @GetMapping("/search/comprehensive")
    public Result comprehensiveSearch(@RequestParam String keyword,
                                    @RequestParam(defaultValue = "1") Integer page,
                                    @RequestParam(defaultValue = "12") Integer size) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return Result.error("搜索关键词不能为空");
            }
            
            String trimmedKeyword = keyword.trim();
            System.out.println("=== 综合搜索开始 ===");
            System.out.println("搜索关键词: " + trimmedKeyword);
            
            // 1. 搜索匹配的分类
            QueryWrapper<CategoryLevel2> categoryQuery = new QueryWrapper<>();
            categoryQuery.eq("status", 1);
            categoryQuery.like("name", trimmedKeyword);
            categoryQuery.orderByAsc("sort_order");
            categoryQuery.last("LIMIT 5"); // 最多返回5个匹配的分类
            
            List<CategoryLevel2> matchedCategories = categoryLevel2Service.list(categoryQuery);
            List<Map<String, Object>> categoriesInfo = new ArrayList<>();
            
            for (CategoryLevel2 category : matchedCategories) {
                Map<String, Object> categoryInfo = new HashMap<>();
                categoryInfo.put("level2Id", category.getLevel2Id());
                categoryInfo.put("name", category.getName());
                categoryInfo.put("icon", category.getIcon());
                
                // 统计该分类下的商品数量
                QueryWrapper<Product> countQuery = new QueryWrapper<>();
                countQuery.eq("level2_id", category.getLevel2Id());
                countQuery.eq("status", 1);
                long productCount = productService.count(countQuery);
                categoryInfo.put("productCount", productCount);
                
                categoriesInfo.add(categoryInfo);
            }
            
            // 2. 搜索匹配的商品
            QueryWrapper<Product> productQuery = new QueryWrapper<>();
            productQuery.eq("status", 1);
            productQuery.like("name", trimmedKeyword);
            productQuery.orderByDesc("avg_score");
            productQuery.orderByDesc("sales_count");
            
            // 分页查询商品
            IPage<Product> pageRequest = new Page<>(page, size);
            IPage<Product> productPage = productService.page(pageRequest, productQuery);
            
            List<Map<String, Object>> productsWithDetails = buildProductInfoList(productPage.getRecords());
            
            // 3. 构建综合搜索结果
            Map<String, Object> response = new HashMap<>();
            response.put("keyword", trimmedKeyword);
            response.put("categories", categoriesInfo);
            response.put("products", productsWithDetails);
            response.put("productTotalCount", productPage.getTotal());
            response.put("categoryTotalCount", matchedCategories.size());
            response.put("currentPage", page);
            response.put("pageSize", size);
            response.put("totalPages", productPage.getPages());
            response.put("hasNext", page < productPage.getPages());
            response.put("hasPrev", page > 1);
            response.put("searchType", "comprehensive");
            
            System.out.println("搜索结果 - 分类: " + matchedCategories.size() + "个, 商品: " + productPage.getTotal() + "个");
            
            return Result.success(response);
        } catch (Exception e) {
            System.err.println("综合搜索失败: " + e.getMessage());
            return Result.error("综合搜索失败：" + e.getMessage());
        }
    }

    // ===== 私有辅助方法 =====
    
    /**
     * 构建商品信息（优化版本 - 参考ProductServiceImpl的高效实现）
     */
    private Map<String, Object> buildProductInfo(Product product) {
        Map<String, Object> productInfo = new HashMap<>();
        productInfo.put("productId", product.getProductId());
        productInfo.put("name", product.getName());
        productInfo.put("price", product.getPrice());
        productInfo.put("originalPrice", product.getOriginalPrice());
        productInfo.put("salesCount", product.getSalesCount());
        productInfo.put("totalReviews", product.getTotalReviews());
        productInfo.put("avgScore", product.getAvgScore());
        productInfo.put("status", product.getStatus());
        productInfo.put("createTime", product.getCreateTime());
        productInfo.put("updateTime", product.getUpdateTime());

        // 计算折扣率（如果有原价）
        if (product.getOriginalPrice() != null && product.getPrice() != null && 
            product.getOriginalPrice().compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal discountRate = product.getOriginalPrice()
                .subtract(product.getPrice())
                .divide(product.getOriginalPrice(), 2, BigDecimal.ROUND_HALF_UP)
                .multiply(new BigDecimal("100"));
            productInfo.put("discountRate", discountRate);
        } else {
            productInfo.put("discountRate", null);
        }

        // 查询商品主图（封面图）
        QueryWrapper<ProductImage> imageQuery = new QueryWrapper<>();
        imageQuery.eq("product_id", product.getProductId());
        imageQuery.eq("type", 0); // 主图
        imageQuery.orderByAsc("sort_order");
        imageQuery.last("LIMIT 1");
        ProductImage coverImage = productImageService.getOne(imageQuery);
        productInfo.put("coverImage", coverImage != null ? coverImage.getImageUrl() : "");

        // 查询商品所有主图（用于商品详情展示）
        QueryWrapper<ProductImage> allImagesQuery = new QueryWrapper<>();
        allImagesQuery.eq("product_id", product.getProductId());
        allImagesQuery.eq("type", 0); // 主图
        allImagesQuery.orderByAsc("sort_order");
        List<ProductImage> allImages = productImageService.list(allImagesQuery);
        List<String> imageUrls = new ArrayList<>();
        for (ProductImage img : allImages) {
            imageUrls.add(img.getImageUrl());
        }
        productInfo.put("images", imageUrls);

        return productInfo;
    }

    /**
     * 批量构建商品信息（高效版本 - 一次查询所有图片）
     */
    private List<Map<String, Object>> buildProductInfoList(List<Product> products) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        if (products.isEmpty()) {
            return result;
        }
        
        // 提取所有商品ID
        List<Long> productIds = new ArrayList<>();
        for (Product product : products) {
            productIds.add(product.getProductId());
        }
        
        // 一次性查询所有商品的封面图片（type=0且sort_order=1）
        QueryWrapper<ProductImage> coverImageQuery = new QueryWrapper<>();
        coverImageQuery.in("product_id", productIds);
        coverImageQuery.eq("type", 0); // 主图
        coverImageQuery.eq("sort_order", 1); // 第一张图作为封面
        List<ProductImage> coverImages = productImageService.list(coverImageQuery);
        
        // 一次性查询所有商品的所有主图
        QueryWrapper<ProductImage> allImagesQuery = new QueryWrapper<>();
        allImagesQuery.in("product_id", productIds);
        allImagesQuery.eq("type", 0); // 主图
        allImagesQuery.orderByAsc("product_id", "sort_order");
        List<ProductImage> allImages = productImageService.list(allImagesQuery);
        
        // 将图片按商品ID分组
        Map<Long, String> coverImageMap = new HashMap<>();
        for (ProductImage img : coverImages) {
            coverImageMap.put(img.getProductId(), img.getImageUrl());
        }
        
        Map<Long, List<String>> allImagesMap = new HashMap<>();
        for (ProductImage img : allImages) {
            allImagesMap.computeIfAbsent(img.getProductId(), k -> new ArrayList<>()).add(img.getImageUrl());
        }
        
        // 构建商品信息
        for (Product product : products) {
            Map<String, Object> productInfo = new HashMap<>();
            productInfo.put("productId", product.getProductId());
            productInfo.put("name", product.getName());
            productInfo.put("price", product.getPrice());
            productInfo.put("originalPrice", product.getOriginalPrice());
            productInfo.put("salesCount", product.getSalesCount());
            productInfo.put("totalReviews", product.getTotalReviews());
            productInfo.put("avgScore", product.getAvgScore());
            productInfo.put("status", product.getStatus());
            productInfo.put("createTime", product.getCreateTime());
            productInfo.put("updateTime", product.getUpdateTime());

            // 计算折扣率（如果有原价）
            if (product.getOriginalPrice() != null && product.getPrice() != null && 
                product.getOriginalPrice().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal discountRate = product.getOriginalPrice()
                    .subtract(product.getPrice())
                    .divide(product.getOriginalPrice(), 2, BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal("100"));
                productInfo.put("discountRate", discountRate);
            } else {
                productInfo.put("discountRate", null);
            }

            // 设置图片信息
            String coverImage = coverImageMap.get(product.getProductId());
            productInfo.put("coverImage", coverImage != null ? coverImage : "");
            
            List<String> images = allImagesMap.get(product.getProductId());
            productInfo.put("images", images != null ? images : new ArrayList<>());
            
            result.add(productInfo);
        }
        
        return result;
    }

    /**
     * 构建港口信息
     */
    private Map<String, Object> buildPortInfo(Ports port) {
        Map<String, Object> portInfo = new HashMap<>();
        portInfo.put("id", port.getId());
        portInfo.put("name", port.getName());
        portInfo.put("portCode", port.getPortCode());
        portInfo.put("description", port.getDescription());
        portInfo.put("region", port.getRegion());
        portInfo.put("timezone", port.getTimezone());
        portInfo.put("isPopular", port.getIsPopular());
        
        // 获取国家信息
        Countries country = countriesService.getById(port.getCountryId());
        if (country != null) {
            portInfo.put("country", country);
        }
        
        return portInfo;
    }

    /**
     * 构建空响应
     */
    private Map<String, Object> buildEmptyResponse(Ports port, Integer page, Integer size) {
        Map<String, Object> response = new HashMap<>();
        response.put("port", buildPortInfo(port));
        response.put("products", new ArrayList<>());
        response.put("totalCount", 0);
        response.put("currentPage", page);
        response.put("pageSize", size);
        response.put("totalPages", 0);
        response.put("hasNext", false);
        response.put("hasPrev", false);
        return response;
    }

    /**
     * 根据港口名称或代码搜索商品
     * @param portName 港口名称或代码
     * @param page 页码，默认1
     * @param size 每页大小，默认12
     */
    @GetMapping("/search/port-products")
    public Result searchProductsByPortName(@RequestParam String portName,
                                         @RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "12") Integer size) {
        try {
            // 搜索匹配的港口
            QueryWrapper<Ports> portQuery = new QueryWrapper<>();
            portQuery.eq("status", 1);
            portQuery.and(wrapper -> wrapper
                .like("name", portName)
                .or()
                .like("port_code", portName)
            );
            portQuery.orderByDesc("is_popular");
            
            List<Ports> matchedPorts = portsService.list(portQuery);
            
            if (matchedPorts.isEmpty()) {
                Map<String, Object> emptyResponse = new HashMap<>();
                emptyResponse.put("ports", new ArrayList<>());
                emptyResponse.put("products", new ArrayList<>());
                emptyResponse.put("totalCount", 0);
                emptyResponse.put("message", "未找到匹配的港口");
                emptyResponse.put("searchKeyword", portName);
                return Result.success(emptyResponse);
            }
            
            // 如果只有一个匹配的港口，直接返回该港口的商品
            if (matchedPorts.size() == 1) {
                Ports port = matchedPorts.get(0);
                return getProductsByPort(port.getId(), page, size, null, "score_desc");
            }
            
            // 如果有多个匹配港口，返回所有匹配港口和部分商品
            List<Map<String, Object>> portsInfo = new ArrayList<>();
            for (Ports port : matchedPorts) {
                Map<String, Object> portInfo = buildPortInfo(port);
                
                // 统计该港口的商品数量
                QueryWrapper<PortProductRelation> countQuery = new QueryWrapper<>();
                countQuery.eq("port_id", port.getId().intValue());
                long productCount = portProductRelationService.count(countQuery);
                portInfo.put("productCount", productCount);
                
                portsInfo.add(portInfo);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("searchType", "multiple_ports");
            response.put("ports", portsInfo);
            response.put("searchKeyword", portName);
            response.put("message", "找到" + matchedPorts.size() + "个匹配的港口");
            
            return Result.success(response);
        } catch (Exception e) {
            return Result.error("搜索港口商品失败：" + e.getMessage());
        }
    }

}
